package git.soulbgm.monitor;

import git.soulbgm.pojo.dto.RedisInfo;
import git.soulbgm.utils.StringUtil;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Redis监控
 *
 * @author SoulBGM
 * @date 2024-10-08
 */
public class RedisMonitor {

    private static RedisConnectionFactory redisConnectionFactory;

    public static void setRedisConnectionFactory(RedisConnectionFactory redisConnectionFactory) {
        RedisMonitor.redisConnectionFactory = redisConnectionFactory;
    }

    public static List<RedisInfo> getRedisInfos() {
        Properties info = redisConnectionFactory.getConnection().info();
        List<RedisInfo> redisInfos = new ArrayList<>(82);
        for (Map.Entry<Object, Object> entry : info.entrySet()) {
            RedisInfo redisInfo = new RedisInfo();
            redisInfo.setKey(StringUtil.objToStr(entry.getKey(), ""));
            redisInfo.setValue(StringUtil.objToStr(entry.getValue(), ""));
            redisInfos.add(redisInfo);
        }
        return redisInfos;
    }

    public static Long getKeysSize() {
        return redisConnectionFactory.getConnection().dbSize();
    }

    public static Long getMemoryInfo() {
        Properties info = redisConnectionFactory.getConnection().info();
        for (Map.Entry<Object, Object> entry : info.entrySet()) {
            String key = StringUtil.objToStr(entry.getKey(), "");
            if ("used_memory".equals(key)) {
                return Long.parseLong(StringUtil.objToStr(entry.getValue(), "0"));
            }
        }
        return 0L;
    }

}
